package com.hngm.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hngm.common.Result;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * Servlet implementation class RotationPicServlet
 */
public class RotationPicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RotationPicServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		//使用smartupload组件实现文件上传
		//1、创建一个SmartUpload对象                                       
		SmartUpload smart = new SmartUpload();
		//2、设置字符编码
		smart.setCharset("utf-8");
		//3、初始化
		smart.initialize(getServletConfig(),request,response);
		
		try {
			//4、文件上传
			smart.upload();
			//5、文件保存到服务器端本地
			String name = System.currentTimeMillis() + ".jpg";	
			smart.getFiles().getFile(0).saveAs("/productpic/rotation/" + name);
			//图片上传成功之后，要把图片的名称返回给前端页面
			String json = Result.toClient(true, "图片上传成功！",name);
			out.print(json);
		} catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			String json = Result.toClient(false, "图片上传失败！","图片格式不正确");
			out.print(json);
		}
		
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
